<?php
/**
 * Глобальный класс управления поиском по сайту
 * 
 * @category Phorm
 * @package Search
 * @name /Phorm/Search.php
 * @copyright phorm.ru
 * @since 03.01.2011
 * @author vladimir@kachalov.net
 */

class Phorm_Search extends Phorm_Model {
	
	/**
	 * Производит поиск по заданному запросу
	 * 
	 * @param string $query Строка для поиска
	 *  
	 * @return boolean
	 */
		
	public function getSearchResults($query) {
			
		if(!$words = $this->getPreparedQuery($query)) return false;
		
		$select = $this->_db->select()
				-> from(array("AA"=>"pw_search_index"),array(
					"resultid" => "SQL_CALC_FOUND_ROWS IF(EE.categoryid IS NULL,BB.resourceid,EE.categoryid)",
					"resultname" => "IF(EE.categoryid IS NULL,BB.resourcename,EE.categoryname)",
					"resultdescr" => "IF(EE.categoryid IS NULL,BB.resourcedescr,EE.categorydescr)",
					"resulturl" => "IF(EE.categoryid IS NULL,CONCAT(DD.fullpath,BB.resourceid,'.html'),EE.fullpath)"))
				-> joinLeft(array("BB"=>"pw_resources"),"AA.resourceid=BB.resourceid",array())
				-> joinLeft(array("CC"=>"pw_resources_categories"),"BB.resourceid=CC.resourceid",array())
				-> joinLeft(array("DD"=>"pw_categories"),"CC.categoryid=DD.categoryid AND DD.fullpath_visible='yes' AND BB.isexist='yes'",array())
				-> joinLeft(array("EE"=>"pw_categories"),"AA.categoryid=EE.categoryid AND EE.fullpath_visible='yes'",array())
				-> where("MATCH (indextitle,indextxt) AGAINST ('".implode(" ",$words)."')")
				-> where("BB.resourceid IS NOT NULL OR EE.categoryid IS NOT NULL")
				-> limitPage($this->getCurrentPage(),$this->getPerPage());
			
		return $this->_db->fetchAll($select);
			
	}
		
		
	/**
	 * Разбирает поисковый запрос на слова, ищет склонения и возвращает массив слов
	 * 
	 * @param string $query Строка для поиска
	 *  
	 * @return array
	 */
		
	protected function getPreparedQuery($query) {
			
		if(preg_match_all("#[a-z0-9а-я]{3,}#iu",$query,$arr)) {
				
			$words = array();
				
			foreach ($arr[0] as $word) $words[] = mb_convert_case($word,MB_CASE_UPPER);
			
			$select = $this->_db->select()
					-> from(array("AA"=>"pw_search_dictionary"), array())
					-> distinct()
					-> join(array("BB"=>"pw_search_dictionary"),"AA.idx=BB.idx",array("word"))
					-> where("AA.word IN('".implode("','",$words)."')")
					-> order("BB.wordid");
				
			return array_unique($words + $this->_db->fetchCol($select));
				
		}
			
		return false;
			
	}
	
}